package com.zshan.clinic.admin.service.config;

import com.zshan.clinic.admin.constant.Constants;
import com.zshan.clinic.admin.entity.vo.*;
import com.zshan.clinic.admin.mapper.config.SpecClinicFeeMapper;
import com.zshan.clinic.admin.service.clinic.ClinicDeptService;
import com.zshan.clinic.admin.service.clinic.ClinicEmpService;
import com.zshan.clinic.common.constant.CommonConstant;
import com.zshan.clinic.common.constant.DictConstant;
import com.zshan.clinic.common.constant.UnitConstant;
import com.zshan.clinic.common.enums.*;
import com.zshan.clinic.common.exception.BusinessFailException;
import com.zshan.clinic.common.util.page.PageInfo;
import com.zshan.clinic.common.util.page.PageUtils;
import com.zshan.clinic.common.util.pinyin.PinyinUtils;
import com.zshan.clinic.common.util.string.StringUtil;
import com.zshan.clinic.database.dao.ClinicDoctorFeeMapper;
import com.zshan.clinic.database.dao.ClinicProjectFeeMapper;
import com.zshan.clinic.database.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 项目收费设置
 */
@Service
@Slf4j
public class ProjectFeeService {

    /**
     * 医生挂号费
     */
    @Autowired
    private ClinicDoctorFeeMapper clinicDoctorFeeMapper;
    /**
     * 收费项目
     */
    @Autowired
    private ClinicProjectFeeMapper clinicProjectFeeMapper;


    @Autowired
    private ClinicEmpService clinicEmpService;

    @Autowired
    private SpecClinicFeeMapper specClinicFeeMapper;

    @Autowired
    private ClinicDeptService clinicDeptService;

    @Autowired
    private ClinicDictService clinicDictService;

    /**
     * 查询医生停诊状态
     * @param clinicId
     * @param empId
     * @return
     */
    public String getDoctorMedicalStatus(Long clinicId, Long empId) {
        ClinicDoctorFee clinicDoctorFee = getClinicDoctorFeeById(empId);
        if(clinicDoctorFee != null
                && StringUtil.isNotBlank(clinicDoctorFee.getIsStopped())
                && clinicDoctorFee.getClinicId().equals(clinicId)){
            return clinicDoctorFee.getIsStopped();
        }
        return YesOrNoEnum.NO.getValue();
    }

    /**
     * 根据助理ID查询医生列表
     * @param assistantId
     * @return
     */
    public List<Long> getDoctorListByAssistantId(Long assistantId){
        ClinicDoctorFeeExample example = new ClinicDoctorFeeExample();
        ClinicDoctorFeeExample.Criteria criteria = example.createCriteria();
        criteria.andAssistantIdEqualTo(assistantId);
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        List<ClinicDoctorFee> doctorFeeList = clinicDoctorFeeMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(doctorFeeList)){
            return Collections.emptyList();
        }
        List<Long> doctorIdList = new ArrayList<>();
        for(ClinicDoctorFee clinicDoctorFee : doctorFeeList){
            doctorIdList.add(clinicDoctorFee.getDoctorId());
        }
        return doctorIdList;
    }


    public List<ClinicProjectFeeCategoryVo> getFeeStandardListV2(Long clinicId, String projectName) {
        List<ClinicProjectFeeStandardVo> feeList = getFeeStandardList(clinicId, null, null, projectName);
        if (CollectionUtils.isEmpty(feeList)) {
            return null; // 或者返回 Collections.emptyList()
        }
        // 字典项 -> 快速查名映射
        Map<String, String> examMap = clinicDictService.getDictItemList(DictConstant.EXAM_TYPE)
                .stream().collect(Collectors.toMap(DictSysItemVo::getItemCode, DictSysItemVo::getItemName, (a, b)->a));
        Map<String, String> labMap = clinicDictService.getDictItemList(DictConstant.LAB_TYPE)
                .stream().collect(Collectors.toMap(DictSysItemVo::getItemCode, DictSysItemVo::getItemName, (a,b)->a));
        Map<String, String> extMap = clinicDictService.getDictItemList(DictConstant.EXT_TYPE)
                .stream().collect(Collectors.toMap(DictSysItemVo::getItemCode, DictSysItemVo::getItemName, (a,b)->a));
        // 结果容器 + 辅助索引，避免频繁遍历
        List<ClinicProjectFeeCategoryVo> categoryList = new ArrayList<>();
        Map<String, ClinicProjectFeeCategoryVo> categoryIdx = new HashMap<>();
        // 每个分类里再建一个“类型”索引（可选，也可改为在 list 里 stream 查找）
        Map<String, Map<String, ClinicProjectFeeTypeVo>> typeIdxByCategory = new HashMap<>();
        for (ClinicProjectFeeStandardVo standardVo : feeList) {
            //大类
            String cat = standardVo.getProjectCategory();
            //小类
            String type = standardVo.getProjectType();

            // 1) 分类对象
            ClinicProjectFeeCategoryVo categoryVo = categoryIdx.get(cat);
            if (categoryVo == null) {
                categoryVo = new ClinicProjectFeeCategoryVo();
                categoryVo.setProjectCategory(cat);
                categoryVo.setProjectCategoryText(ProjectCategoryEnum.getText(cat));
                categoryVo.setTypeList(new ArrayList<>());
                categoryList.add(categoryVo);
                categoryIdx.put(cat, categoryVo);
                typeIdxByCategory.put(cat, new HashMap<>());
            }
            // 2) 类型对象
            Map<String, ClinicProjectFeeTypeVo> typeIdx = typeIdxByCategory.get(cat);
            ClinicProjectFeeTypeVo typeVo = typeIdx.get(type);
            if (typeVo == null) {
                typeVo = new ClinicProjectFeeTypeVo();
                typeVo.setProjectType(type);
                // 按分类映射名称
                String typeText = null;
                if (Objects.equals(ProjectCategoryEnum.EXAM.getValue(), cat)) {
                    typeText = examMap.get(type);
                } else if (Objects.equals(ProjectCategoryEnum.LAB.getValue(), cat)) {
                    typeText = labMap.get(type);
                } else if (Objects.equals(ProjectCategoryEnum.EXT.getValue(), cat)) {
                    typeText = extMap.get(type);
                }
                if (typeText != null) {
                    typeVo.setProjectTypeText(typeText);
                }
                typeVo.setFeeList(new ArrayList<>());
                categoryVo.getTypeList().add(typeVo);
                typeIdx.put(type, typeVo);
            }

            // 3) 加入费用标准
            typeVo.getFeeList().add(standardVo);
        }
        return categoryList;
    }


    /**
     * 查询收费列表-模板选择项目用
     * @param clinicId
     * @param projectCategory
     * @param projectType
     * @param projectName
     * @return
     */
    public List<ClinicProjectFeeStandardVo> getFeeStandardList(Long clinicId, String projectCategory, String projectType, String projectName) {
        if(StringUtil.isNotBlank(projectName)){
            projectCategory = null;
            projectType = null;
        }
        List<String> projectCategoryList = new ArrayList<>();
        if(StringUtil.isBlank(projectCategory)){
            //如果为空，默认检查检验项目
            projectCategoryList.add(ProjectCategoryEnum.EXAM.getValue());
            projectCategoryList.add(ProjectCategoryEnum.LAB.getValue());
        }else {
            projectCategoryList.add(projectCategory);
        }
        return specClinicFeeMapper.getFeeStandardList(clinicId,projectCategoryList,projectType,projectName);
    }

    /**
     * 查询所有的收费项目
     * @param clinicId
     * @return
     */
    public List<ClinicProjectCategoryVo> getAllFeeList(Long clinicId) {
        return specClinicFeeMapper.getAllFeeList(clinicId);
    }

    /**
     * 获取有效的查验项目
     * @param projectIds
     * @return
     */
    public List<ClinicProjectFee> getEnabledClinicProjectFeeList(List<Long> projectIds,List<String> projectCategoryList) {
        ClinicProjectFeeExample example = new ClinicProjectFeeExample();
        ClinicProjectFeeExample.Criteria criteria = example.createCriteria();
        criteria.andProjectIdIn(projectIds);
        if(!CollectionUtils.isEmpty(projectCategoryList)){
            criteria.andProjectCategoryIn(projectCategoryList);
        }
        criteria.andIsEnabledEqualTo(YesOrNoEnum.YES.getValue());
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        return clinicProjectFeeMapper.selectByExample(example);
    }


    /**
     * 获取医生下拉框列表
     * @param clinicId
     * @return
     */
    public List<ClinicDoctorSelectVo> getSelectList(Long clinicId){
        return specClinicFeeMapper.getSelectList(clinicId);
    }


    /**
     * 查询医生挂号费列表
     * @param doctorName
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<ClinicDoctorFeeVo> getDoctorFeeList(Long clinicId, String doctorName, Long deptId, Integer pageNo, Integer pageSize) {
        Long totalCount = specClinicFeeMapper.getDoctorFeeCount(clinicId,doctorName,deptId);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<ClinicDoctorFeeVo> feeList = specClinicFeeMapper.getDoctorFeeList(clinicId,doctorName,deptId,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,feeList);
    }

    /**
     * 查询收费项目列表
     * @param clinicId
     * @param projectCategory
     * @param projectName
     * @param deptId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<ClinicProjectFeeVo> getProjectFeeList(Long clinicId, String projectCategory, String projectType,String projectName,Long deptId, Integer pageNo, Integer pageSize) {
        if(StringUtil.isBlank(projectCategory)){
            return PageInfo.build();
        }
        Long totalCount = specClinicFeeMapper.getProjectFeeCount(clinicId,projectCategory,projectType,projectName,deptId);
        if(StringUtil.isBlank(totalCount)){
            return PageInfo.build();
        }
        List<ClinicProjectFeeVo> feeList = specClinicFeeMapper.getProjectFeeList(clinicId,projectCategory,projectType,projectName,deptId,PageUtils.getOffset(pageNo,pageSize),pageSize);
        return new PageInfo<>(totalCount,feeList);
    }


    /**
     * 查询医生挂号费列表
     * @param doctorId
     * @param pageNo
     * @param pageSize
     * @return
     */
    public PageInfo<ClinicDoctorFee> getClinicDoctorFeeListByCondition(Long doctorId, Integer pageNo, Integer pageSize) {
        ClinicDoctorFeeExample example = new ClinicDoctorFeeExample();
        ClinicDoctorFeeExample.Criteria criteria = example.createCriteria();
        if (doctorId != null) {
            criteria.andDoctorIdEqualTo(doctorId);
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = clinicDoctorFeeMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<ClinicDoctorFee> list = clinicDoctorFeeMapper.selectByExample(example);
        return new PageInfo<>(totalCount, list);
    }

    /**
     * 添加医生挂号费
     * @param doctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void addDoctorFee(ClinicDoctorFee doctorFee) {
        validateClinicDoctorFee(doctorFee);
        ClinicDoctorFee clinicDoctorFee = getClinicDoctorFeeById(doctorFee.getDoctorId());
        if(clinicDoctorFee != null){
            throw new BusinessFailException("当前医生已经添加挂号费，请更换后重试！");
        }
        doctorFee.setIsStopped(YesOrNoEnum.NO.getValue());
        doctorFee.setIsDelete(YesOrNoEnum.NO.getValue());
        doctorFee.setIsEnabled(YesOrNoEnum.YES.getValue());
        doctorFee.setCreateTime(new Date());
        clinicDoctorFeeMapper.insertSelective(doctorFee);
    }

    /**
     * 验证医生挂号费数据合法性（可扩展）
     * @param doctorFee
     */
    public void validateClinicDoctorFee(ClinicDoctorFee doctorFee) {
        //实现必要校验逻辑，如 doctorId、挂号费金额非空等
        ClinicEmp clinicEmp = clinicEmpService.getEnabledEmpById(doctorFee.getDoctorId());
        if(clinicEmp == null || !clinicEmp.getClinicId().equals(doctorFee.getClinicId())){
            throw new BusinessFailException("医生不存在");
        }
        if(doctorFee.getVisitTime() == null || doctorFee.getVisitTime() <= CommonConstant.DEFAULT_0){
            throw new BusinessFailException("看病时段必须大于"+CommonConstant.DEFAULT_0);
        }
        if(doctorFee.getFirstVisitFee() == null || doctorFee.getFirstVisitFee() <= CommonConstant.DEFAULT_0){
            throw new BusinessFailException("初诊费用必须大于"+CommonConstant.DEFAULT_0);
        }
        if(doctorFee.getFollowUpFee() == null || doctorFee.getFollowUpFee() <= CommonConstant.DEFAULT_0){
            throw new BusinessFailException("复诊费用必须大于"+CommonConstant.DEFAULT_0);
        }
        if(doctorFee.getEmergencyFee() == null || doctorFee.getEmergencyFee() <= CommonConstant.DEFAULT_0){
            throw new BusinessFailException("急诊费用必须大于"+CommonConstant.DEFAULT_0);
        }
        if(doctorFee.getAppointmentFee() == null || doctorFee.getAppointmentFee() <= CommonConstant.DEFAULT_0){
            throw new BusinessFailException("预约费用必须大于"+CommonConstant.DEFAULT_0);
        }
        if(!StringUtil.isBlank(doctorFee.getAssistantId())){
            ClinicEmp assistant = clinicEmpService.getEnabledEmpById(doctorFee.getAssistantId());
            if(assistant == null || !assistant.getClinicId().equals(doctorFee.getClinicId())){
                throw new BusinessFailException("助理不存在");
            }
        }
    }

    /**
     * 根据ID获取医生挂号费
     * @param doctorId
     * @return
     */
    public ClinicDoctorFee getClinicDoctorFeeById(Long doctorId) {
        if (StringUtil.isBlank(doctorId)) {
            return null;
        }
        ClinicDoctorFee clinicDoctorFee = clinicDoctorFeeMapper.selectByPrimaryKey(doctorId);
        if (clinicDoctorFee == null || YesOrNoEnum.YES.getValue().equals(clinicDoctorFee.getIsDelete())) {
            return null;
        }
        return clinicDoctorFee;
    }

    /**
     * 根据ID获取医生挂号费
     * @param doctorId
     * @return
     */
    public ClinicDoctorFee getEnabledClinicDoctorFeeById(Long doctorId) {
        ClinicDoctorFee clinicDoctorFee = getClinicDoctorFeeById(doctorId);
        if (clinicDoctorFee == null || YesOrNoEnum.NO.getValue().equals(clinicDoctorFee.getIsEnabled())) {
            return null;
        }
        return clinicDoctorFee;
    }

    /**
     * 修改医生挂号费
     * @param clinicDoctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateDoctorFee(ClinicDoctorFee clinicDoctorFee) {
        validateClinicDoctorFee(clinicDoctorFee);
        ClinicDoctorFee dbClinicDoctorFee = getClinicDoctorFeeById(clinicDoctorFee.getDoctorId());
        if (dbClinicDoctorFee == null) {
            throw new BusinessFailException("医生挂号费不存在");
        }
        clinicDoctorFee.setUpdateTime(new Date());
        clinicDoctorFeeMapper.updateByPrimaryKeySelective(clinicDoctorFee);
    }

    /**
     * 删除医生挂号费（逻辑删除）
     * @param doctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteDoctorFee(ClinicDoctorFee doctorFee) {
        ClinicDoctorFee dbFee = getClinicDoctorFeeById(doctorFee.getDoctorId());
        if (dbFee == null) {
            throw new BusinessFailException("医生挂号费不存在");
        }
        clinicDoctorFeeMapper.deleteByPrimaryKey(dbFee.getDoctorId());
    }

    /**
     * 启用医生挂号费
     * @param doctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableDoctorFee(ClinicDoctorFee doctorFee) {
        ClinicDoctorFee dbFee = getClinicDoctorFeeById(doctorFee.getDoctorId());
        if (dbFee == null) {
            throw new BusinessFailException("医生挂号费不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbFee.getIsEnabled())) {
            return;
        }
        dbFee.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbFee.setUpdateUserId(doctorFee.getUpdateUserId());
        dbFee.setUpdateBy(doctorFee.getUpdateBy());
        dbFee.setUpdateTime(new Date());
        clinicDoctorFeeMapper.updateByPrimaryKeySelective(dbFee);
    }

    /**
     * 停用医生挂号费
     * @param doctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableDoctorFee(ClinicDoctorFee doctorFee) {
        ClinicDoctorFee dbFee = getClinicDoctorFeeById(doctorFee.getDoctorId());
        if (dbFee == null) {
            throw new BusinessFailException("医生挂号费不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbFee.getIsEnabled())) {
            return;
        }
        dbFee.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbFee.setUpdateUserId(doctorFee.getUpdateUserId());
        dbFee.setUpdateBy(doctorFee.getUpdateBy());
        dbFee.setUpdateTime(new Date());
        clinicDoctorFeeMapper.updateByPrimaryKeySelective(dbFee);
    }


    /**
     * 暂停接诊
     * @param doctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void stopReception(ClinicDoctorFee doctorFee) {
        ClinicDoctorFee dbFee = getClinicDoctorFeeById(doctorFee.getDoctorId());
        if (dbFee == null) {
            throw new BusinessFailException("医生挂号费不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbFee.getIsStopped())) {
            return;
        }
        dbFee.setIsStopped(YesOrNoEnum.YES.getValue());
        dbFee.setUpdateUserId(doctorFee.getUpdateUserId());
        dbFee.setUpdateBy(doctorFee.getUpdateBy());
        dbFee.setUpdateTime(new Date());
        clinicDoctorFeeMapper.updateByPrimaryKeySelective(dbFee);
    }

    /**
     * 恢复接诊
     * @param doctorFee
     */
    @Transactional(rollbackFor = Exception.class)
    public void resumeReception(ClinicDoctorFee doctorFee) {
        ClinicDoctorFee dbFee = getClinicDoctorFeeById(doctorFee.getDoctorId());
        if (dbFee == null) {
            throw new BusinessFailException("医生挂号费不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbFee.getIsStopped())) {
            return;
        }
        dbFee.setIsStopped(YesOrNoEnum.NO.getValue());
        dbFee.setUpdateUserId(doctorFee.getUpdateUserId());
        dbFee.setUpdateBy(doctorFee.getUpdateBy());
        dbFee.setUpdateTime(new Date());
        clinicDoctorFeeMapper.updateByPrimaryKeySelective(dbFee);
    }


    /**
     * 分页查询检查项目收费设置
     * @param projectName 检查项目名（可选条件）
     * @param pageNo 页码
     * @param pageSize 每页条数
     * @return 分页结果
     */
    public PageInfo<ClinicProjectFee> getClinicProjectFeeListByCondition(String projectName, Integer pageNo, Integer pageSize) {
        ClinicProjectFeeExample example = new ClinicProjectFeeExample();
        ClinicProjectFeeExample.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotBlank(projectName)) {
            criteria.andProjectNameLike("%"+projectName+"%");
        }
        criteria.andIsDeleteEqualTo(YesOrNoEnum.NO.getValue());
        Long totalCount = clinicProjectFeeMapper.countByExample(example);
        if (totalCount == null || totalCount == 0) {
            return PageInfo.build();
        }
        example.setOffset(PageUtils.getOffset(pageNo, pageSize));
        example.setLimit(pageSize);
        example.setOrderByClause("create_time desc");
        List<ClinicProjectFee> list = clinicProjectFeeMapper.selectByExample(example);
        return new PageInfo<>(totalCount, list);
    }

    /**
     * 添加检查项目收费
     * @param clinicProjectFee 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void addProjectFee(ClinicProjectFee clinicProjectFee) {
        validateClinicExamFee(clinicProjectFee);
        clinicProjectFee.setIsDelete(YesOrNoEnum.NO.getValue());
        clinicProjectFee.setIsEnabled(YesOrNoEnum.YES.getValue());
        clinicProjectFee.setCreateTime(new Date());
        clinicProjectFeeMapper.insertSelective(clinicProjectFee);
    }


    /**
     * 校验检查项目收费参数
     * @param clinicProjectFee 实体
     */
    public void validateClinicExamFee(ClinicProjectFee clinicProjectFee) {
        // 可加入唯一性、非空校验
        String projectCategory = clinicProjectFee.getProjectCategory();
        if(StringUtil.isBlank(projectCategory)){
            throw new BusinessFailException("项目分类不能为空");
        }
        if(!ProjectCategoryEnum.isValue(projectCategory)){
            throw new BusinessFailException("项目分类错误");
        }
        clinicProjectFee.setProjectName(StringUtil.removeAllWhitespace(clinicProjectFee.getProjectName()));
        if (StringUtil.isBlank(clinicProjectFee.getProjectName())) {
            throw new BusinessFailException("项目名称不能为空");
        }
        if(clinicProjectFee.getProjectName().length() > Constants.EXAM_PROJECT_LENGTH){
            throw new BusinessFailException("项目名称"+Constants.EXAM_PROJECT_LENGTH+"个字以内！");
        }
        clinicProjectFee.setProjectPinyin(PinyinUtils.getFirstLetters(clinicProjectFee.getProjectName()));
        String dictCode = null;
        if(ProjectCategoryEnum.EXAM.getValue().equals(projectCategory)){
            //检查项目
            dictCode = DictConstant.EXAM_TYPE;
        }else if(ProjectCategoryEnum.LAB.getValue().equals(projectCategory)){
            //检验项目
            dictCode = DictConstant.LAB_TYPE;
            String sampleType = clinicProjectFee.getSampleType();
            if(StringUtil.isBlank(sampleType)){
                throw new BusinessFailException("样本类型不能为空");
            }
            if(!LabSampleTypeEnum.isValue(sampleType)){
                throw new BusinessFailException("样本类型错误");
            }
        }else if (ProjectCategoryEnum.EXT.getValue().equals(projectCategory)){
            //理疗项目
            dictCode = DictConstant.EXT_TYPE;
        }
        if(!clinicDictService.isDictValue(dictCode,clinicProjectFee.getProjectType())){
            throw new BusinessFailException("项目类型错误");
        }
        if(ProjectCategoryEnum.EXT.getValue().equals(clinicProjectFee.getProjectCategory())){
            if(StringUtil.isBlank(clinicProjectFee.getChargeType())){
                throw new BusinessFailException("请选择收费类型");
            }
            if(!ProjectChargeTypeEnum.isValue(clinicProjectFee.getChargeType())){
                throw new BusinessFailException("收费类型错误");
            }
            if(ProjectChargeTypeEnum.ACUPOINT.getValue().equals(clinicProjectFee.getChargeType())){
                clinicProjectFee.setUnit(UnitConstant.xue);
            }else {
                clinicProjectFee.setUnit(UnitConstant.ci);
            }
        }else {
            clinicProjectFee.setChargeType(ProjectChargeTypeEnum.ITEM.getValue());
            if (StringUtil.isBlank(clinicProjectFee.getUnit())) {
                throw new BusinessFailException("单位不能为空");
            }
        }
        DictUnitVo dictUnitVo = clinicDictService.getUnitValue(UnitTypeEnum.PROJECT.getValue(),clinicProjectFee.getUnit());
        if(dictUnitVo == null){
            throw new BusinessFailException("单位类型错误");
        }
        clinicProjectFee.setUnitText(dictUnitVo.getUnitText());
        if (clinicProjectFee.getPrice() == null || clinicProjectFee.getPrice() <= CommonConstant.DEFAULT_0) {
            throw new BusinessFailException("销售价格必须大于"+CommonConstant.DEFAULT_0);
        }
        ClinicDept clinicDept = clinicDeptService.getEnabledClinicDeptById(clinicProjectFee.getDeptId());
        if(clinicDept == null || !clinicDept.getClinicId().equals(clinicProjectFee.getClinicId())){
            throw new BusinessFailException("科室不存在");
        }
    }

    public ClinicProjectFee getEnabledClinicProjectFeeById(Long projectId) {
        ClinicProjectFee clinicProjectFee = getClinicProjectFeeById(projectId);
        if(clinicProjectFee == null){
            return null;
        }
        if(YesOrNoEnum.NO.getValue().equals(clinicProjectFee.getIsEnabled())){
            return null;
        }
        return clinicProjectFee;
    }

    /**
     * 根据ID查询检查项目收费
     * @param projectId 主键
     * @return 检查项目收费记录
     */
    public ClinicProjectFee getClinicProjectFeeById(Long projectId) {
        if (StringUtil.isBlank(projectId)) {
            return null;
        }
        ClinicProjectFee clinicProjectFee = clinicProjectFeeMapper.selectByPrimaryKey(projectId);
        if (clinicProjectFee == null || YesOrNoEnum.YES.getValue().equals(clinicProjectFee.getIsDelete())) {
            return null;
        }
        return clinicProjectFee;
    }

    /**
     * 修改检查项目收费
     * @param clinicProjectFee 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateProjectFee(ClinicProjectFee clinicProjectFee) {
        validateClinicExamFee(clinicProjectFee);
        ClinicProjectFee dbClinicProjectFee = getClinicProjectFeeById(clinicProjectFee.getProjectId());
        if (dbClinicProjectFee == null) {
            throw new BusinessFailException("项目不存在");
        }
        clinicProjectFee.setUpdateTime(new Date());
        clinicProjectFeeMapper.updateByPrimaryKeySelective(clinicProjectFee);
    }

    /**
     * 删除检查项目收费（逻辑删除）
     * @param clinicProjectFee 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteProjectFee(ClinicProjectFee clinicProjectFee) {
        ClinicProjectFee dbClinicProjectFee = getClinicProjectFeeById(clinicProjectFee.getProjectId());
        if (dbClinicProjectFee == null) {
            throw new BusinessFailException("项目不存在");
        }
        dbClinicProjectFee.setIsDelete(YesOrNoEnum.YES.getValue());
        dbClinicProjectFee.setUpdateUserId(clinicProjectFee.getUpdateUserId());
        dbClinicProjectFee.setUpdateBy(clinicProjectFee.getUpdateBy());
        dbClinicProjectFee.setUpdateTime(new Date());
        clinicProjectFeeMapper.updateByPrimaryKeySelective(dbClinicProjectFee);
    }

    /**
     * 启用检查项目收费
     * @param clinicProjectFee 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void enableProjectFee(ClinicProjectFee clinicProjectFee) {
        ClinicProjectFee dbClinicProjectFee = getClinicProjectFeeById(clinicProjectFee.getProjectId());
        if (dbClinicProjectFee == null) {
            throw new BusinessFailException("项目不存在");
        }
        if (YesOrNoEnum.YES.getValue().equals(dbClinicProjectFee.getIsEnabled())) {
            return;
        }
        dbClinicProjectFee.setIsEnabled(YesOrNoEnum.YES.getValue());
        dbClinicProjectFee.setUpdateUserId(clinicProjectFee.getUpdateUserId());
        dbClinicProjectFee.setUpdateBy(clinicProjectFee.getUpdateBy());
        dbClinicProjectFee.setUpdateTime(new Date());
        clinicProjectFeeMapper.updateByPrimaryKeySelective(dbClinicProjectFee);
    }

    /**
     * 停用检查项目收费
     * @param clinicProjectFee 实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void disableProjectFee(ClinicProjectFee clinicProjectFee) {
        ClinicProjectFee dbClinicProjectFee = getClinicProjectFeeById(clinicProjectFee.getProjectId());
        if (dbClinicProjectFee == null) {
            throw new BusinessFailException("项目不存在");
        }
        if (YesOrNoEnum.NO.getValue().equals(dbClinicProjectFee.getIsEnabled())) {
            return;
        }
        dbClinicProjectFee.setIsEnabled(YesOrNoEnum.NO.getValue());
        dbClinicProjectFee.setUpdateUserId(clinicProjectFee.getUpdateUserId());
        dbClinicProjectFee.setUpdateBy(clinicProjectFee.getUpdateBy());
        dbClinicProjectFee.setUpdateTime(new Date());
        clinicProjectFeeMapper.updateByPrimaryKeySelective(dbClinicProjectFee);
    }

}
